package net.lulihu.pangolin.headless.common.util;

import io.netty.channel.Channel;
import io.netty.util.AttributeKey;

/**
 * 通道双向绑定工具
 */
public class ChannelTwoWayBindKit {

    /**
     * 用户通道与代理通道进行双向绑定
     */
    private static final AttributeKey<Channel> CHANNEL_TWO_WAY_BINDING = AttributeKey.newInstance("channel_twoWayBinding");

    /**
     * 双向绑定通道
     *
     * @param channel1 通道1
     * @param channel2 通道2
     */
    public static void twoWayBindingChannel(Channel channel1, Channel channel2) {
        channel1.attr(CHANNEL_TWO_WAY_BINDING).set(channel2);
        channel2.attr(CHANNEL_TWO_WAY_BINDING).set(channel1);
    }

    /**
     * 获取绑定通道
     *
     * @param channel 通道
     * @return 绑定的通道
     */
    public static Channel getBindChannel(Channel channel) {
        return channel.attr(CHANNEL_TWO_WAY_BINDING).get();
    }

    /**
     * 解除通道绑定
     *
     * @param channel1 通道1
     * @param channel2 通道2
     */
    public static void unbind(Channel channel1, Channel channel2) {
        unbind(channel1);
        unbind(channel2);
    }

    /**
     * 解除通道绑定
     *
     * @param channel 通道
     */
    public static void unbind(Channel channel) {
        if (channel != null) channel.attr(CHANNEL_TWO_WAY_BINDING).set(null);
    }

}
